'use strict'

import { app, protocol, BrowserWindow,ipcMain } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
const isDevelopment = process.env.NODE_ENV !== 'production'

protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true,stream: true } }
])
let win=null;
    console.log(process.env.NODE_ENV)
//stream:true加载视频，否则白屏
async function createWindow() {
 win = new BrowserWindow({
    width: 1920,
    height: 1080,
    frame: false,
    fullscreen: process.env.NODE_ENV==='development'?false:true,
    useContentSize: false,
   // resizable: false,
    webPreferences: {
      nodeIntegration: true, // 使渲染进程拥有node环境
      webSecurity: false
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }
  win.setAlwaysOnTop(true);//窗口置顶
}

app.setLoginItemSettings({openAtLogin: true})//开机自启动
//app.commandLine.appendSwitch('autoplay-policy', 'no-user-gesture-required');
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

app.on('ready', async () => {
  createWindow()
    registerLocalVideoProtocol()
    function registerLocalVideoProtocol () {
        protocol.registerFileProtocol('local-video', (request, callback) => {
            const url = request.url.replace(/^local-video:\/\//, '')
            const path=require('path')
            // Decode URL to prevent errors when loading filenames with UTF-8 chars or chars like "#"
            const decodedUrl = decodeURI(url) // Needed in case URL contains spaces
            try {
                // eslint-disable-next-line no-undef
                return callback(path.join(__static, decodedUrl))//这步是路径指向public目录
            } catch (error) {
                console.error(
                    'ERROR: registerLocalVideoProtocol: Could not get file path:',
                    error
                )
            }
        })
    }
})
ipcMain.on('open-devtools',(event,arg)=>{
  win.webContents.openDevTools()
})
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}
